<?php
/* This notice must be untouched at all times.

newviewer.php    v. 2.2
This file is part of PhyloGeoViz
The latest version is available at
http://www.phylogeoviz.com

Copyright (c) 2007 Yi-Hsin Erica Tsai. All rights reserved.
Created 15.7.2007 by Yi-Hsin Erica Tsai (Web: http://www.duke.edu/~yet2)
Last modified: 20.8.2007

PhyloGeoViz is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

PhyloGeoViz is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

// $_REQUEST is the global array that contains the submitted data.
// The array has an element for each form variable that was submitted.
// In our case we just have the text area, so count($_REQUEST) = 1.
// You can reference elements in the arrays by more than their numerical
// location.  You can call them by their "name". Ex: $_REQUEST["phylodata"]

function pv ($var)
{
	echo "<pre>";
	var_dump($var);
	echo "</pre>\n";
}
$numpops = $_REQUEST["numpops"];
$numhaps = $_REQUEST["numhaps"];
$pop_names = json_decode(stripslashes($_REQUEST["pop_names"])); //json_decode is the php function that parses encoded JSON objects (evalJSON() was the javascript function)
$hap_names = json_decode(stripslashes($_REQUEST["hap_names"])); 
$pop_lat = json_decode(stripslashes($_REQUEST["pop_lat"])); 
$pop_lng = json_decode(stripslashes($_REQUEST["pop_lng"])); 
$pop_haps = json_decode(stripslashes($_REQUEST["pop_haps"])); 
$hapgroups = json_decode(stripslashes($_REQUEST["hapgroups"])); 
$pop_include = json_decode(stripslashes($_REQUEST["pop_include"])); //json_decode 
$hap_include = json_decode(stripslashes($_REQUEST["hap_include"])); //json_decode
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<title>PhyloGeoViz Map</title>
		<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAxhj9keQ-W_pSFQOerM1zcxQDzKVN9nYxJYcr0zvm4oc_VslaGBS9ekLzJd0hyV9ctr3fGo93wfu7EA"
			type="text/javascript"></script>
		<link type="text/css" rel="stylesheet" href="javascripts/colorpicker/colorPicker.css" />
		<link type="text/css" rel="stylesheet" href="phylogeoviz.css" />
		<link type="text/css" rel="stylesheet" href="previewstyle.css" />
		<script type="text/javascript" src="javascripts/jquery-1.1.3.1.js"></script>
		<script type="text/javascript" src="javascripts/prototype.js"></script>
		<script type="text/javascript" src="javascripts/wz_jsgraphics.js"></script>
		<script type="text/javascript" src="javascripts/scriptaculous.js"></script>
		<script type="text/javascript" src="javascripts/colorpicker/yahoo.color.js"></script>
		<script type="text/javascript" src="javascripts/colorpicker/colorPicker.js"></script>
		<script type="text/javascript" src="phylogeovizmapfunctions.js"></script>
		<script type="text/javascript">
		//<![CDATA[
		//The above line is for XML parsers.  Just leave it.

		jQuery.noConflict();  //tells jQuery not to use '$'; prototype does instead

		//GLOBAL VARIABLES
		var numpops;
		var numhaps;  //not the full data, only those that are included
		var pop_names;  //array of strings that store the names of each population.  The length of pop_names = numpops.
		var hap_names;  //not the full data, only those that are included
		var pop_centers;  
		var pop_haps;  //not the full data, only those that are included
		var hapgroups;  //not the full data, only those that are included; the group name for each haplotype
		var pop_include;
		var hap_include;
		var radii_in_km // = [40, 50, 65] by default;
		var hap_colors;  //not the full data, only those that are included
		var pop_hapthetas;  //not the full data, only those that are included
		var map;
		var pop_radii;  //array of radii for each population
		var numbins = 3;  //number of different pie sizes
		var bindivs = [1, 5];  //array of boundary values for each of the bins.  Ex: if = [1, 5], there are 3 bins, <1, 2-5, 5+.  Note, count(bindivs) is always one smaller than numbins.
		var radii_in_px;  //array of radii for each pie size in pixels
		var full_numhaps;
		var full_pop_haps;
		var full_hapgroups;
		var full_hap_names;
		var numgroups;  //number of haplotype groups
		var uniquegroups;  //the names of the haplotype groups
			
		function load() 
		{

		  if (navigator.appName == "Microsoft Internet Explorer")
		  {
			  $("browserisIE").setStyle({
				  'display': 'block'
			  });
		  }

		  if (GBrowserIsCompatible()) 
		  {
			//map and map features
			map = new GMap2(document.getElementById("map"));

			//////////////// get data saved from passed form elements ////////////
			//declare variables			
<?php
	echo "\t\t\tnumpops = ".$numpops.";\n";
	echo "\t\t\tfull_numhaps = ".$numhaps.";\n";
	echo "\t\t\tpop_names = new Array();\n";
	echo "\t\t\tfull_hap_names = new Array();\n";
	echo "\t\t\thap_names = new Array();\n";
	echo "\t\t\tpop_centers = new Array();\n";
	echo "\t\t\tfull_pop_haps = new Array();\n";
	echo "\t\t\tfull_hapgroups = new Array();\n";
	echo "\t\t\tpop_haps = new Array();\n";
	echo "\t\t\thapgroups = new Array();\n";
	echo "\t\t\tpop_include = new Array();\n";
	echo "\t\t\thap_include = new Array();\n";
	echo "\t\t\tnumgroups = 0;\n";
	echo "\t\t\tuniquegroups = new Array();\n";
	echo "\t\t\tpop_radii = new Array();\n";
?>

			//set variable values
<?php
	for ($h = 0; $h < $numhaps; $h++)
	{
		echo "\t\t\tfull_hapgroups[".$h."] = \"".$hapgroups[$h]."\";\n";
		echo "\t\t\tfull_hap_names[".$h."] = \"".$hap_names[$h]."\";\n";
		echo "\t\t\thap_include[".$h."] = ".$hap_include[$h].";\n";
	}

	for ($p = 0; $p < $numpops; $p++)
	{
		echo "\t\t\tpop_names[".$p."] = \"".$pop_names[$p]."\";\n";
		echo "\t\t\tpop_include[".$p."] = ".$pop_include[$p].";\n";
		echo "\t\t\tpop_centers[".$p."] = new GLatLng({$pop_lat[$p]}, {$pop_lng[$p]});\n";
		echo "\t\t\tfull_pop_haps[{$p}] = new Array();\n";
		echo "\t\t\tpop_haps[{$p}] = new Array();\n";
		
		for ($h = 0; $h < $numhaps; $h++)
		{
			echo "\t\t\tfull_pop_haps[".$p."][".$h."] = ".$pop_haps[$p][$h].";\n";
		}
	}
?>
			//continue setting map variables
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GScaleControl());

			var avgcenter = [0, 0];
			for (p = 0; p < numpops; ++p)
			{
				avgcenter[0] += pop_centers[p].lng();
				avgcenter[1] += pop_centers[p].lat();
			}
			avgcenter[0] = avgcenter[0] / numpops;
			avgcenter[1] = avgcenter[1] / numpops;				
			map.setCenter(new GLatLng(avgcenter[1], avgcenter[0]), 5);
			var givenmaptypes = map.getMapTypes();
			map.setMapType(givenmaptypes[1]);  //google sometimes changes the variable names for the various maptypes, so it's best to check it this way.


			//sort all of the haplotypes by their haplotype group
			var sortorder = getsortarrayorder(full_hapgroups);
			full_hapgroups = sortarray(full_hapgroups, sortorder);
			full_hap_names = sortarray(full_hap_names, sortorder);
			hap_include = sortarray(hap_include, sortorder);
			for (var p = 0; p < numpops; ++p)
				full_pop_haps[p] = sortarray(full_pop_haps[p], sortorder);

			//define the subset pop_haps and hapgroups that are 'included'
			var temp = 0;
			for (var fh = 0; fh < full_numhaps; ++fh)
			{
				if (numgroups == 0 && hap_include[fh] == 1)
				{
					hapgroups[temp] = full_hapgroups[fh];
					hap_names[temp] = full_hap_names[fh];

					for (var p = 0; p < numpops; ++p)
						pop_haps[p][temp] = full_pop_haps[p][fh];

					uniquegroups.push(hapgroups[temp]);

					temp = temp + 1;
					numgroups = numgroups + 1;
				}

				else if (hap_include[fh] == 1) //if 'included'
				{
					hapgroups[temp] = full_hapgroups[fh];
					hap_names[temp] = full_hap_names[fh];

					for (var p = 0; p < numpops; ++p)
						pop_haps[p][temp] = full_pop_haps[p][fh];

					if (uniquegroups[numgroups - 1] != hapgroups[temp])
					{
						uniquegroups.push(hapgroups[temp]);
						numgroups = numgroups + 1;
					}

					temp = temp + 1;
				}
			}

			numhaps = temp;

			//set the view of the map to show all the populations
			var maxlat = maxmatrix(pop_centers, "lat");
			var maxlng = maxmatrix(pop_centers, "lng");
			var minlat = minmatrix(pop_centers, "lat");
			var minlng = minmatrix(pop_centers, "lng");
			var newbounds = new GLatLngBounds(new GLatLng(minlat-0.5, minlng-0.5), new GLatLng(maxlat+0.5, maxlng+0.5));
			map.setCenter(newbounds.getCenter());
			map.setZoom(map.getBoundsZoomLevel(newbounds));

			//Display the pies for the read in information previously processed by php.
			//The colors of the haplotypes are the same across populations.  

			//set pie sizes
<?php 		
		if(array_key_exists("radii_in_km", $_REQUEST))
		{
			$radii_in_km = json_decode(stripslashes($_REQUEST["radii_in_km"]));

			echo "\t\t\tradii_in_km = new Array();";
			for ($i = 0; $i < count($radii_in_km); $i++)
				echo "\t\t\tradii_in_km[".$i."] = \"".$radii_in_km[$i]."\";\n";
		}

		else
			echo "\t\t\tradii_in_km = [40, 50, 65];\n";
?>		
			pop_radii = setdefaultradii(numpops, numhaps, pop_haps, numbins, bindivs, radii_in_km);

			//randomly generate haplotype colors if they aren't already set
<?php
		if(array_key_exists("set_hap_colors", $_REQUEST))
		{
			$matrix_hap_colors = json_decode(stripslashes($_REQUEST["set_hap_colors"]));
			
			echo "\t\tset_hap_colors = new Array();\n"; //an array with haplotype names is indices and values as the already set colors

			for ($i = 0; $i < count($matrix_hap_colors); $i++)
				echo "\t\tset_hap_colors[\"".$matrix_hap_colors[$i][0]."\"] = \"".$matrix_hap_colors[$i][1]."\";\n";
?>
			hap_colors = new Array();
			for (var h = 0; h < numhaps; ++h)
			{
				if(set_hap_colors[hap_names[h]])  //if it exists, so color is already set
				{
					hap_colors[h] = set_hap_colors[hap_names[h]];
				}
				else  //color not set yet, so get random color
				{
					hap_colors[h] = RGB2Color(rand(255),rand(255),rand(255));
				}
			}
<?php
		}
		
		else
		{
?>
			hap_colors = new Array();
			for (var i = 0; i < numhaps; ++i)
			{
				hap_colors.push(RGB2Color(rand(255),rand(255),rand(255)));
				//stores the colors for each haplotype
			}
<?php
		}
?>	

			//must convert pop_haps to appropriate pop_hapthetas
			pop_hapthetas = new Array();
			
			
			//create a div to house all the pies as a child of the "map"
			//this div will eventually get moved within a 'gmnoprint' div
			var piesdiv = document.createElement("div");
			piesdiv.id = "piesdiv";
			document.getElementById("map").appendChild(piesdiv);
//			console.log(piesdiv);
			
			new PeriodicalExecuter(svg_organizer, 0.001);
			
			for (var i = 0; i < numpops; ++i)
			{
				pop_hapthetas[i] = new Array();
				pop_hapthetas[i].push(0);
				for (var j = 0; j < (numhaps - 1); ++j)
				{
					pop_hapthetas[i].push((pop_haps[i][j] * 360 / sumarray(pop_haps[i])) 
						+ pop_hapthetas[i][j]);		
				}
				pop_hapthetas[i].push(360);

				//draw the pie and make it draggable
				//but only draw it if the pop_include is true
				if (pop_include[i])
				{
					drawpie(map, i, pop_radii[i], pop_centers[i], pop_hapthetas[i], hap_colors);
//					var test1 = document.getElementsByTagName('svg');
//					console.log("after draw pie", i, test1);
//					var test3 = map.getPane(G_MAP_MAP_PANE);
//					test3.addClassName("pies" + i);
//					console.log(test3);
//					var test2 = test1[0];
//					console.log(test2);
//					Element.addClassName(test2, "gotcha");
			
				}
			}

			radii_in_px = calc_radiiinpx(map, numbins, radii_in_km);
			drawpiesizelegend(numbins, bindivs, radii_in_px, "popsizelegend");  //draw sample size table divs
			
			var mapproj = G_NORMAL_MAP.getProjection();  //for fromPixelToLatLng(pixel, zoom,  unbounded?)

			// Drawing the Haplotype Legend

			var legendnode = $("hapcolorlegend");  //where all the table elements will go

			createHapLegend(legendnode);

			// Make sure the map redraws the pies correctly on zooming
			GEvent.addListener(map, "zoomend", function (oldLevel, newLevel) 
			{
				//clear old pie info
				map.clearOverlays();

				clearpiedivs(numpops);

				//draw new pies
				for (var i = 0; i <numpops; ++i)
				{
					if (pop_include[i])
						drawpie(map, i, pop_radii[i], pop_centers[i], pop_hapthetas[i], hap_colors);
				}
				
				new PeriodicalExecuter(svg_organizer, 0.001);
				
				//redraw the legend after zooming
				radii_in_px = calc_radiiinpx(map, numbins, radii_in_km);
				drawpiesizelegend(numbins, bindivs, radii_in_px, "popsizelegend");  
			});

			//reset the pies and make them draggable and editable after the maptype changes.
			GEvent.addListener(map, "maptypechanged", function () 
			{
				//clear old pie info
				map.clearOverlays();

				clearpiedivs(numpops);

				//draw new pies
				for (var i = 0; i <numpops; ++i)
				{
					if (pop_include[i])
						drawpie(map, i, pop_radii[i], pop_centers[i], pop_hapthetas[i], hap_colors);
				}
				
				new PeriodicalExecuter(svg_organizer, 0.001);
			});
		  }  
		}
    	//]]>
    	</script>
    </head>

	<body onload="load()" onunload="GUnload()">
		<div id="page">
			<div id="browserisIE" class="hidden">
				<h2>I&rsquo;m sorry!  This software does NOT work in Internet Explorer.  Try it in <a href="http://www.mozilla.com/en-US/firefox/">Firefox</a>, please.</h2>
			</div>  	
			<h2>Your PhyloGeoViz map</h2>
			<div id="map" style="width: 600px; height: 500px"></div>
			<div id="seccolumn">
				<div id="legend">
				<!-- have a div for each haplotype -->
					<h2>Legend and Options</h2>
					<p>Click on the <span class="plus">+</span> to expand an option and edit your map.</p>
					<div id="colorlegend" class="widget">
						<h3 class="widgetHead"><span class="clickable" onclick="toggleBlock('colorlegend')">+ Haplotype colors</span></h3>
						<div class="widgetBody">
							<p>To edit a color, click on the appropriate colorbox. Click the <span class="plus">+</span> to expand and edit individual haplotypes.</p>
							<div id="hapcolorlegend" name="hapcolorlegend">
							<!-- the table elemens for the haplotype groups -->
							</div>
						</div>
					</div>
					<div id="popsizelegend" class="widget">
						<h3 class="widgetHead"><span class="clickable" onclick="toggleBlock('popsizelegend')">+ Sample sizes</span></h3>
						<div class="widgetBody">
							<table>
								<tr>
									<td>Change pie size: </td>
									<td><input type="button" id="piesmaller" name="piesmaller" value="-" onclick="piesize('-');">
									<input type="button" id="pielarger" name="pielarger" value="+" onclick="piesize('+');"></td>
							</tr>
						</table>
						</div>
					</div>

					<!-- Make buttons that control the size of the pies -->
					<div id="pieoptions" class="widget">
						<h3 class="widgetHead"><span class="clickable" onclick="toggleBlock('pieoptions')">+ Pie options</span></h3>
						<div class="widgetBody">
							<table>
								<tr>
									<td>Change pie size: </td>
									<td><input type="button" id="piesmaller" name="piesmaller" value="-" onclick="piesize('-');">
									<input type="button" id="pielarger" name="pielarger" value="+" onclick="piesize('+');"></td>
								</tr>
								<tr>
									<td id="outlineheader" name="outlineheader">Outline pie wedges: </td>
									<td><input type="checkbox" id="outline" name="outline" value="show" onclick="drawoutline(this.checked);"> 
								</tr>
								<tr>
									<td>Edit data values: </td>
									<td>
										<div id="editdata">
											<form id="datatoedit" name="datatoedit" method="post" action="editdata.php">
												<input type="hidden" id="numpops" name="numpops" />
												<input type="hidden" id="full_numhaps" name="full_numhaps" />
												<input type="hidden" id="pop_names" name="pop_names" />
												<input type="hidden" id="full_hap_names" name="full_hap_names" />		
												<input type="hidden" id="pop_lat" name="pop_lat" />
												<input type="hidden" id="pop_lng" name="pop_lng" />
												<input type="hidden" id="full_pop_haps" name="full_pop_haps" />
												<input type="hidden" id="full_hapgroups" name="full_hapgroups" />
												<input type="hidden" id="pop_include" name="pop_include" />
												<input type="hidden" id="hap_include" name="hap_include" />
												<input type="hidden" id="uniquegroups" name="uniquegroups" />
												<input type="hidden" id="radii_in_km" name="radii_in_km" />
												<input type="hidden" id="set_hap_colors" name="set_hap_colors" />
												<input type="submit" value="Edit Data" onclick="serializetoeditpage();" />
											</form>
										</div>
									</td>
								</tr>
							</table>
						</div>
					</div>

					<div id="mapoptions" class="widget">
						<h3 class="widgetHead"><span class="clickable" onclick="toggleBlock('mapoptions')">+ Map options</span></h3>
						<div class="widgetBody">
							<table>
								<tr>
									<td>Change map size: </td>
									<td><input type="button" id="mapsmaller" name="mapsmaller" value="-" onclick="mapsize('-');">
									<input type="button" id="maplarger" name="maplarger" value="+" onclick="mapsize('+');"></td>
								</tr>
							</table>   			
						</div>
					</div>

					<div id="exportoptions" class="widget">
						<h3 class="widgetHead"><span class="clickable" onclick="toggleBlock('exportoptions')">+ Export options</span></h3>
						<div class="widgetBody">
							<form id="exportform" name="exportform" action="export.php" method="post" />
								<input type="hidden" id="expnumpops" name="expnumpops" />
								<input type="hidden" id="expnumhaps" name="expnumhaps" />
								<input type="hidden" id="exppop_names" name="exppop_names" />
								<input type="hidden" id="exphap_names" name="exphap_names" />
								<input type="hidden" id="exppop_centers" name="exppop_centers" />
								<input type="hidden" id="exppop_haps" name="exppop_haps" />
								<input type="hidden" id="exphapgroups" name="exphapgroups" />
								<input type="hidden" id="exppop_include" name="exppop_include" />
								<input type="hidden" id="exppop_radii" name="exppop_radii" />
								<input type="hidden" id="exphap_colors" name="exphap_colors" />
								<input type="hidden" id="exppop_hapthetas" name="exppop_hapthetas" />
								<input type="hidden" id="outline_checked" name="outline_checked" />
								<input type="submit" value="Export to Google Earth" onclick="serializeexportdata();" />
							</form>
						</div>
					</div>
				</div>
				<p><a href="index.html">Start completely over!</a></p>   	
			</div>
		</div>
	</body>
</html>
